package com.david.shortcuts;

import static com.david.shortcuts.ShortCutsProxyService.SHORT_CUTS_KEY;
import static com.david.shortcuts.ShortCutsProxyService.SHORT_CUTS_ONE_KEY_LOCK;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;


public class OneKeyLockWidget extends AppWidgetProvider {
    public static final String PANEL_VIEW_CLICK = "com.oitsme.PANEL_VIEW_CLICK";

    /**
     * 桌面小部件更新回调方法，设置view的UI及事件；通过playService的updateWidget触发系统开始更新桌面部件
     */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {

        for (int appWidgetId : appWidgetIds) {
            RemoteViews remoteViews = getWidgetView(context);

            if (remoteViews == null) {
                return;
            }
//            // 调用集合管理器对集合进行更新
            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }


    public static RemoteViews getWidgetView(Context context) {
        // 获取AppWidget对应的视图
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.one_key_lock_widget);

//        // TODO: 2023/9/14 直接使用路由跳转，替换service代理跳转
        /**8.0后用getForegroundService才能在app被kill后直接启动service*/
        Intent aliScanIntent = new Intent(context, ShortCutsProxyService.class);
//        Intent aliScanIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("alipays://platformapi/startapp?saId=10000007"));
        aliScanIntent.setAction(PANEL_VIEW_CLICK);
        aliScanIntent.putExtra(SHORT_CUTS_KEY, SHORT_CUTS_ONE_KEY_LOCK);
        //打开activity时用PendingIntent.getActivity, 启动service时用getService,发送广播时使用getBroadcast
        PendingIntent aliscanPendingIntent =
                PendingIntent.getForegroundService(context, 1000, aliScanIntent, PendingIntent.FLAG_IMMUTABLE);

        remoteViews.setOnClickPendingIntent(R.id.one_key_lock_parent, aliscanPendingIntent);
        return remoteViews;

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        Log.e("shortcuts", "refresh widget");
    }
}
